<template>
  <el-dialog
    v-model="props.modelValue"
    width="1000px"
    :show-close="false"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <template #header="{ close, titleId, titleClass }">
      <div class="my-header">
        <h4
          :id="titleId"
          :class="titleClass"
        >
          {{ t(`dockRepair.btn9`) }}
        </h4>
        <img
          src="@/assets/img/icon_guanbi.png"
          @click="close"
          class="close"
        />
      </div>
    </template>

    <div class="step1">
      <el-tabs
        v-model="activeName"
        @tab-change="tabChange"
      >
        <el-tab-pane
          :label="item.projectName"
          :name="index"
          v-for="(item, index) in tabData"
          :disabled="activeStep === 1"
        >
        </el-tab-pane>
      </el-tabs>

      <div class="title">{{ t('dockRepair.step2page.pipeline.t1') }}：</div>

      <div class="item mt-1">
        <!-- <div class="tit">{{ t('dockRepair.step2page.pipeline.tit1') }}</div> -->
        <div class="con flexsc">
          <div
            :class="['li', 'mr-1', { active: s1ActiveList.includes(index) }]"
            v-for="(item, index) in s1"
            :key="index"
            @click="handleSelect(index, s1ActiveList)"
          >
            {{ item.projectName }}
          </div>
        </div>
      </div>

      <div class="item mt-1">
        <!-- <div class="tit">{{ t('dockRepair.step2page.pipeline.tit2') }}</div> -->
        <div class="con flexsc">
          <div
            :class="['li', 'mr-1', { active: s2ActiveList.includes(index) }]"
            v-for="(item, index) in s2"
            :key="index"
            @click="handleSelect(index, s2ActiveList)"
          >
            {{ item.projectName }}
          </div>
        </div>
      </div>

      <div class="item mt-1">
        <!-- <div class="tit">{{ t('dockRepair.step2page.pipeline.tit3') }}</div> -->
        <div class="con flexsc">
          <div
            :class="['li', 'mr-1', { active: s3ActiveList.includes(index) }]"
            v-for="(item, index) in s3"
            :key="index"
            @click="handleSelect(index, s3ActiveList)"
          >
            {{ item.projectName }}
          </div>
        </div>
      </div>

      <div class="res mt-2 flexsc nowrap">
        <div class="mr-1">{{ t('dockRepair.step2page.valve.res') }}：</div>
        <el-input
          v-model="resValue"
          :disabled="activeStep === 1"
          style="width: 710px"
        ></el-input>
        <img
          src="@/assets/img/icon_bianji.png"
          class="ml-1 mr-3"
        />
        <el-button
          type="primary"
          @click="handleNext"
          :disabled="activeStep === 1"
        >
          {{ t('confirmText') }}
        </el-button>
      </div>

      <div
        class="res flexsc nowrap"
        style="margin-top: 2px"
      >
        <div
          class="mr-1"
          style="visibility: hidden"
        >
          {{ t('dockRepair.step2page.valve.res') }}：
        </div>
        <el-input
          v-model="resValue2"
          :disabled="activeStep === 1"
          style="width: 710px"
        ></el-input>
        <img
          src="@/assets/img/icon_bianji.png"
          class="ml-1 mr-3"
        />
      </div>
    </div>

    <div class="step2 mt-5">
      <div class="title">{{ t('dockRepair.step2page.pipeline.t2') }}：</div>

      <el-form :disabled="activeStep === 0">
        <!--  -->
        <div class="main mt-1">
          <div
            class="grid-3"
            style="column-gap: 20px"
          >
            <div class="item">
              <div class="label">{{ t('dockRepair.step2page.pipeline.l1') }}</div>
              <el-input-number
                v-model="formData.a"
                placeholder=""
                :min="0"
                :controls="false"
              >
              </el-input-number>
              <div class="append">mm</div>
            </div>
            <div class="item">
              <div class="label">{{ t('dockRepair.step2page.pipeline.l2') }}</div>
              <el-input-number
                v-model="formData.b"
                placeholder=""
                :min="0"
                :controls="false"
              >
              </el-input-number>
              <div class="append">m</div>
            </div>
            <div class="item">
              <div class="label">{{ t('dockRepair.step2page.pipeline.l3') }}</div>
              <el-input-number
                v-model="formData.aaa"
                placeholder=""
                :min="0"
                :controls="false"
                @blur="onBlur('dockRepair.step2page.pipeline.l3', 'aaa')"
                @keyup.enter="onBlur('dockRepair.step2page.pipeline.l3', 'aaa')"
              >
              </el-input-number>
              <div class="append">{{ t('dockRepair.step2page.pipeline.u1') }}</div>
            </div>

            <div class="item">
              <div class="label">{{ t('dockRepair.step2page.pipeline.l9') }}</div>
              <el-input-number
                v-model="formData.ccc"
                :placeholder="t('dockRepair.step2page.pipeline.l9_p1')"
                :min="0"
                :controls="false"
                @blur="onBlur2('cccddd', 'ccc')"
                @keyup.enter="onBlur2('cccddd', 'ccc')"
              >
              </el-input-number>
              <div class="append">mm</div>
            </div>

            <div class="item">
              <div class="label">{{ t('dockRepair.step2page.pipeline.l11') }}</div>
              <el-input-number
                v-model="formData.ddd"
                placeholder=""
                :min="0"
                :controls="false"
                @blur="onBlur2('cccddd', 'ddd')"
                @keyup.enter="onBlur2('cccddd', 'ddd')"
              >
              </el-input-number>
              <div class="append">m</div>
            </div>

            <div class="item">
              <div class="label">{{ t('dockRepair.step2page.pipeline.l4') }}</div>
              <el-input-number
                v-model="formData.bbb"
                placeholder=""
                :min="0"
                :controls="false"
                @blur="onBlur('dockRepair.step2page.pipeline.l4', 'bbb')"
                @keyup.enter="onBlur('dockRepair.step2page.pipeline.l4', 'bbb')"
              >
              </el-input-number>
              <div class="append">{{ t('dockRepair.step2page.pipeline.u1') }}</div>
            </div>

            <div class="item">
              <div class="label">{{ t('dockRepair.step2page.pipeline.l6') }}</div>
              <el-input-number
                v-model="formData.ggg"
                placeholder=""
                :min="0"
                :controls="false"
                @blur="onBlur('dockRepair.step2page.pipeline.l6', 'ggg')"
                @keyup.enter="onBlur('dockRepair.step2page.pipeline.l6', 'ggg')"
              >
              </el-input-number>
              <div class="append">{{ t('dockRepair.step2page.pipeline.u1') }}</div>
            </div>

            <div class="item">
              <div class="label">{{ t('dockRepair.step2page.pipeline.l5') }}</div>
              <el-input-number
                v-model="formData.fff"
                placeholder=""
                :min="0"
                :controls="false"
                @blur="onBlur('dockRepair.step2page.pipeline.l5', 'fff')"
                @keyup.enter="onBlur('dockRepair.step2page.pipeline.l5', 'fff')"
              >
              </el-input-number>
              <div class="append">{{ t('dockRepair.step2page.pipeline.u1') }}</div>
            </div>

            <div class="item">
              <div class="label">{{ t('dockRepair.step2page.pipeline.l7') }}</div>
              <el-input-number
                v-model="formData.hhh"
                placeholder=""
                :min="0"
                :controls="false"
                @blur="onBlur('dockRepair.step2page.pipeline.l7', 'hhh')"
                @keyup.enter="onBlur('dockRepair.step2page.pipeline.l7', 'hhh')"
              >
              </el-input-number>
              <div class="append">{{ t('dockRepair.step2page.pipeline.u1') }}</div>
            </div>

            <div class="item">
              <div class="label">{{ t('dockRepair.step2page.pipeline.l12') }}</div>
              <el-input-number
                v-model="formData.eee"
                placeholder=""
                :min="0"
                :controls="false"
                @blur="onBlur('dockRepair.step2page.pipeline.l12', 'eee')"
                @keyup.enter="onBlur('dockRepair.step2page.pipeline.l12', 'eee')"
              >
              </el-input-number>
              <div class="append">{{ t('dockRepair.step2page.pipeline.u1') }}</div>
            </div>

            <div class="item">
              <div class="label">{{ t('dockRepair.step2page.pipeline.l8') }}</div>
              <el-input-number
                v-model="formData.iii"
                placeholder=""
                :min="0"
                :controls="false"
                @blur="onBlur('dockRepair.step2page.pipeline.l8', 'iii')"
                @keyup.enter="onBlur('dockRepair.step2page.pipeline.l8', 'iii')"
              >
              </el-input-number>
              <div class="append">{{ t('dockRepair.step2page.pipeline.u1') }}</div>
            </div>
          </div>
        </div>

        <div class="bottom mt-1 flexss">
          <div
            style="line-height: 32px; width: 80px"
            class="flexec mr-1"
          >
            {{ t('dockRepair.step2page.valve.res2') }}
          </div>
          <div>
            <div
              class="item"
              v-for="(item, index) in resData"
              :key="index"
            >
              <div>
                <el-input
                  v-model="item.projectName"
                  :maxlength="50"
                ></el-input>
                <el-input
                  v-model="item.projectName2"
                  :maxlength="50"
                  style="margin-top: 2px"
                ></el-input>
              </div>
              <template v-if="index !== 0">
                <div><el-input v-model="item.requireCount" @change="onChangeCount(item)"></el-input></div>
                <div style="line-height: 30px">{{ item.unit }}</div>
              </template>
              <template v-else>
                <img
                  src="@/assets/img/icon_bianji.png"
                  class="mr-3"
                />
              </template>
            </div>
          </div>
        </div>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer flexcc">
        <el-button
          color="#252628"
          plain
          @click="cancel"
        >
          {{ t('cancelText') }}
        </el-button>
        <el-button
          :disabled="activeStep === 0"
          type="primary"
          color="#252628"
          @click="confirm()"
        >
          {{ t('confirmText') }}
        </el-button>
        <el-button
          v-if="activeStep === 1"
          type="primary"
          color="#252628"
          @click="confirm(true)"
        >
          {{ t('dockRepair.step2page.pipeline.b1') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, nextTick, watch, onBeforeMount, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { batchInsertApi, finishOrderBatchInsertApi, getAddOnPipeAboutApi, insertAddOnApi, finishOrderInsertAddOnApi } from '@/service/dockOrder'
import useDockRepair from '@/stores/dockRepair.js'
import zh from '@/lang/zh.json'
import en from '@/lang/en.json'

const { t, locale } = useI18n()
const store = useDockRepair()

onBeforeMount(() => {
  getOptions()
})

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  checkedRow: {
    type: Object,
    default: () => null
  },
  shipType: {
    type: String,
    default: ''
  },
  isFinishOrder: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'getData'])

const handleClose = () => {
  emit('update:modelValue', false)
}

// 取消
const cancel = () => {
  handleClose()
}

//
const activeStep = ref(0)
const activeName = ref(null)
const tabData = ref([])
const tabChange = (val) => {
  s1ActiveList.value = []
  s2ActiveList.value = []
  s3ActiveList.value = []
}
const s1 = computed(() => {
  return tabData.value[activeName.value]?.detailPlace
})
const s2 = computed(() => {
  return tabData.value[activeName.value]?.detailName
})
const s3 = computed(() => {
  return tabData.value[activeName.value]?.detailRequest
})
const getOptions = () => {
  getAddOnPipeAboutApi({
    shipType: props.shipType
  }).then(({ data }) => {
    tabData.value = data
    activeName.value = 0
  })
}

// 第一步
const s1ActiveList = ref([])
const s2ActiveList = ref([])
const s3ActiveList = ref([])
const handleSelect = (val, list) => {
  if (activeStep.value === 1) return
  const index = list.findIndex((item) => item === val)
  if (index !== -1) {
    list.splice(index, 1)
  } else {
    list.push(val)
  }
}
const resValue = ref('') // 第一语言
const resValue2 = ref('') // 第二语言
watch(
  [activeName, s1ActiveList, s2ActiveList, s3ActiveList],
  ([activeName, s1ActiveList, s2ActiveList, s3ActiveList]) => {
    const s = ' '

    const fn = (key) => {
      const active = tabData.value[activeName][key]
      const s1ActiveListName = s1ActiveList.map((item) => s1.value[item][key])
      const s2ActiveListName = s2ActiveList.map((item) => s2.value[item][key])
      const s3ActiveListName = s3ActiveList.map((item) => s3.value[item][key])

      let str = `${active}${s}${s1ActiveListName.join(s)}${s}${s2ActiveListName.join(s)}`

      if (s3ActiveListName.length) {
        str += `,${s3ActiveListName.join()}`
      }

      return str
    }

    resValue.value = fn('projectName')
    if (locale.value === 'zh-CN') {
      resValue2.value = fn('projectNameEn')
    }
    if (locale.value === 'en') {
      resValue2.value = fn('projectNameCn')
    }
  },
  {
    deep: true
  }
)

const afterCheckedId = ref(null)
// 下一步
const handleNext = () => {
  const api = !props.isFinishOrder ? insertAddOnApi : finishOrderInsertAddOnApi
  api({
    addOnDetailList: [{ projectName: resValue.value, projectName2: resValue2.value }],
    projectParent: props.checkedRow.id
  }).then(({ data }) => {
    activeStep.value++
    afterCheckedId.value = data
    ElMessage.success(t('saveSuccess'))
    emit('getData')
  })
}

// 第二步
const formData = ref({})
const resData = ref([{}])
watch(
  formData,
  (n) => {
    const lang_obj = {
      'zh-CN': 'en',
      en: 'zh'
    }

    try {
      resData.value[0] = {
        projectName: `${t('dockRepair.step2page.pipeline.l1')} ${n.a || 0}mm, ${t('dockRepair.step2page.pipeline.l2')} ${n.b || 0}m`,
        projectName2: `${eval(`${lang_obj[locale.value]}.dockRepair.step2page.pipeline.l1`)} ${n.a || 0}mm, ${eval(`${lang_obj[locale.value]}.dockRepair.step2page.pipeline.l2`)} ${n.b || 0}m`,
        requireCount: n.b || 0,
        unit: 'm',
        unit2: 'm'
      }
    } catch (error) {
      console.log(error)
    }
  },
  {
    deep: true
  }
)

const onBlur = (projectName, key, unit = 'dockRepair.step2page.pipeline.u1') => {
  const requireCount = formData.value[key]
  let projectName2 = ''
  let unit2 = ''
  try {
    if (locale.value === 'zh-CN') {
      projectName2 = eval('en.' + projectName)
      unit2 = eval('en.' + unit)
    }
    if (locale.value === 'en') {
      projectName2 = eval('zh.' + projectName)
      unit2 = eval('zh.' + unit)
    }

    const obj = {
      projectName: t(projectName),
      projectName2,
      requireCount,
      unit: t(unit),
      unit2,
      key
    }
    if(!resData.value.filter(item => item?.key === key).length) resData.value.push(obj)
    resData.value.find(item => item?.key === key).requireCount = requireCount
  } catch (error) {
    console.log(error)
  }
}

const onChangeCount = ({ key, requireCount }) => {
  formData.value[key] = Number(requireCount)
}

const onBlur2 = (key = '', valueKey = '') => {
  const projectName = `${t('dockRepair.step2page.pipeline.l10')}${formData.value.ccc || 0}mm, ${t('dockRepair.step2page.pipeline.l2')} ${formData.value.ddd || 0}m`
  const requireCount = 1.5
  const lang_obj = {
    'zh-CN': 'en',
    en: 'zh'
  }

  try {
    const projectName2 = `${eval(`${lang_obj[locale.value]}.dockRepair.step2page.pipeline.l10`)}${formData.value.ccc || 0}mm, ${eval(`${lang_obj[locale.value]}.dockRepair.step2page.pipeline.l2`)} ${formData.value.ddd || 0}m`
    const obj = {
      projectName,
      projectName2,
      requireCount,
      unit: 'm',
      unit2: 'm',
      key
    }
    if(!resData.value.filter(item => item?.key === key).length) resData.value.push(obj)
    else {
      resData.value.forEach(item => {
        if (item?.key === key) {
          item.projectName = projectName
          item.projectName2 = projectName2
        }
      })
    }
  } catch (error) {
    console.log(error)
  }
}

// 重置
const reset = () => {
  activeStep.value = 0
  getOptions()
  formData.value = {}
  resData.value = [{}]
  s1ActiveList.value = []
  s2ActiveList.value = []
  s3ActiveList.value = []
  afterCheckedId.value = null
}

// 确定
const confirm = (isContinue = false) => {
  const api = !props.isFinishOrder ? batchInsertApi : finishOrderBatchInsertApi
  api({
    addOnDetailList: resData.value,
    projectParent: afterCheckedId.value
  }).then(() => {
    ElMessage.success(t('saveSuccess'))
    emit('getData')

    if (isContinue) {
      reset()
    } else {
      handleClose()
    }
  })
}
</script>

<style scoped lang="scss">
.title {
  font-weight: bold;
  color: #252628;
  &::before {
    content: '';
    display: inline-block;
    width: 4px;
    height: 12px;
    background: var(--mainColor);
    margin-right: 8px;
  }
}
.step1 {
  .item {
    .li {
      padding: 5px 10px;
      cursor: pointer;
      margin-top: 3px;
      background: #fae9e5;

      &.active {
        background: var(--mainColor);
        color: #fff;
        border-color: var(--mainColor);
      }
    }
  }
}
.step2 {
  .main {
    padding: 0 115px 0 20px;

    .item {
      margin-bottom: 10px;
      display: grid;
      grid-template-columns: 80px 90px auto;
      gap: 10px;
      align-items: center;
      .label {
        text-align: right;
      }

      :deep(.el-input-number) {
        width: 90px;
      }
    }
  }

  .bottom {
    padding-left: 20px;
    .item {
      display: grid;
      grid-template-columns: 553px 90px 30px;
      gap: 10px;
      // align-items: center;
      margin-bottom: 10px;

      &:first-of-type {
        grid-template-columns: 553px 30px;
      }
    }
  }
}
</style>
